package com.zhou.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhou.constant.RedisConstant;
import com.zhou.dao.SetmealMapper;
import com.zhou.entity.PageResult;
import com.zhou.pojo.Setmeal;
import com.zhou.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
@Component
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private JedisPool jedisPool;

    //@Value("${out_put_path}")//从属性文件读取输出目录的路径
    private String outputpath = "E:/health_parent/health_parent/health_mobile/src/main/webapp/pages";


    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealMapper.insert(setmeal);
        //保存套餐 图片路径保存到redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        }
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    //生成静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("setmeal", this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_" + setmeal.getId() + ".html",
                    dataMap);
        }
    }

    private void generateHtml(String templateName, String htmlPageName, HashMap<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        BufferedWriter out = null;
        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成数据
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outputpath + "/" + htmlPageName))));
            //输出文件
            template.process(dataMap, out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeals = setmealMapper.pageQuery(queryString);
        return new PageResult(setmeals.getTotal(), setmeals.getResult());
    }

    @Override
    public void deleteById(Integer id) {
        //删除关联表数据
        setmealMapper.deleteAssociation(id);
        //删除主表数据
        setmealMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkGroupIds) {
        setmealMapper.updateByPrimaryKeySelective(setmeal);
        //删除所有的现有关系
        setmealMapper.deleteAssociation(setmeal.getId());
        //重新建立关系
        setSetmealAndCheckGroup(setmeal.getId(), checkGroupIds);
    }

    //建立套餐和检查组的联系
    public void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkGroupIds) {
        if (checkGroupIds != null && checkGroupIds.length > 0) {
            for (Integer checkGroupId : checkGroupIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", setmealId);
                map.put("checkgroup_id", checkGroupId);
                setmealMapper.setSetmealAndCheckGroup(map);
            }
        }
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmaealId(Integer id) {
        return setmealMapper.findCheckGroupIdsBySetmaealId(id);
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealMapper.findAll();
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealMapper.findSetmealCount();
    }
}
